package com.bootdo.collection.utils;
import com.bootdo.collection.domain.PushStationDO;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class UploadFtpUtil {
    /**
     * @param picturesStream
     * @param pushStationDO
     * @param type 图片类型 true为普通图集，false为缩略图
     * @return
     */
    public static R upload(List<Map<Integer,InputStream>> picturesStream, PushStationDO pushStationDO, boolean type){
         InputStream inputStream;
        //创建客户端对象
        FTPClient ftp = getFTPClient(pushStationDO.getPushFtpAdress(),pushStationDO.getPushFtpPassword(),pushStationDO.getPushFtpUser(),pushStationDO.getPushFtpPort());
        try {
            // 设置PassiveMode传输
            ftp.enterLocalPassiveMode();
            // 设置以二进制流的方式传输
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //设置上传路径
            String path= getPath(ftp,type);
            //图片名称集合
            List<String> imageList = new ArrayList<>();
            for(Map<Integer,InputStream> streamMap:picturesStream){
                inputStream = streamMap.get(pushStationDO.getPushStationId());
                //文件名
                String fileName = StringUtils.replaceAll(UUID.randomUUID().toString() + ".jpg","-","");
                imageList.add(pushStationDO.getPushImagePrefix() + path + fileName);
                ftp.storeFile(path+fileName,inputStream);
                //将指针位置归零
                inputStream.reset();
            }
            HashMap<String,Object> map = new HashMap();
            //代表上传成功
            map.put("code",0);
//            if(type){
                map.put("imageList",imageList);
//            }else {//缩略图只有一张
//                String thumbUrl = imageList.get(0);
//                int start = pushStationDO.getPushImagePrefix().length() + "Thumb".length();
//                thumbUrl = thumbUrl.substring(start);
//                map.put("thumbUrl",thumbUrl);
//            }
            map.put("path",path.substring(path.indexOf("/")));
            return R.ok(map);
        } catch (SocketException e) {
            e.printStackTrace();
            return R.error();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        } finally {
            try {
                //退出
                ftp.logout();
                //断开连接
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param ftpClient ftp客户端
     * @param type 图片类型，true为图集，false为缩略图
     * @return
     */
    private static String getPath(FTPClient ftpClient,boolean type){
        Date currentDate = new Date();
        String dateStr=new SimpleDateFormat("yyyy/MMdd").format(currentDate);
        String path;
        if(type){
            path = "Pics/"+dateStr+"/c_";
            int atlasCount = getAtalasCount(ftpClient,path);
            if(atlasCount < 10){
                path += "0"+Integer.toString(atlasCount)+"/";
            }else {
                path += Integer.toString(atlasCount)+"/";
            }
        }else {
            path = "Thumb/" + dateStr + "/";
        }
        String combinePath = new String();
        for(String pathStr:path.split("/")){
            combinePath+=pathStr+"/";
            try {
                 ftpClient.makeDirectory(combinePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    /**
     * 得到当天上传的图集数量
     * @return
     */
    public static int getAtalasCount(FTPClient ftpClient,String path){
//        try {
//            PropertiesConfiguration conf = new PropertiesConfiguration("record-atlas.properties");
//            //配置文件中记录的天数
//            String recordDay = (String)conf.getProperty("record.day");
//            //当天上传的图集
//            String atlasCount = (String)conf.getProperty("atlas.count");
//            String currentDay = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//            //如果是同一天，则累计上传图集
//            if(currentDay.equals(recordDay)){
//                atlasCount = String.valueOf(Integer.parseInt(atlasCount) + 1);
//                conf.setProperty("atlas.count",atlasCount);
//                //处理图集少于两位数的情况,
//                if(Integer.parseInt(atlasCount) < 10){
//                    atlasCount = "0" + atlasCount;
//                }
//                conf.save();
//                return atlasCount;
//            }else {//不是当天，则更新日期同时将图集数量重置
//                conf.setProperty("record.day",currentDay);
//                conf.setProperty("atlas.count",1);
//                conf.save();
//                return "01";
//            }
//        } catch (ConfigurationException e) {
//            e.getStackTrace();
//        }
//        return null;
        int max = 0;
        try {
            String[] fileNames = ftpClient.listNames(path.substring(0,path.indexOf("c_")));
            int count;
            for(String fileName: fileNames){
                if(!fileName.contains("c_")){
                    continue;
                }
                try {
                    count = Integer.parseInt(fileName.substring("c_".length()));
                }catch (Exception e){
                    continue;
                }
                if(max < count){
                    max = count;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
       return ++max;
}

    public static FTPClient getFTPClient(String ftpHost, String ftpPassword,
                                         String ftpUserName, int ftpPort) {
        FTPClient ftpClient = null;
        Logger logger = LoggerFactory.getLogger(UploadFtpUtil.class);
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        }
        System.out.println("---------------------连接成功----------------------");
        System.out.println(ftpClient);
        return ftpClient;
    }
}
